package com.android.plc.ui.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.android.plc.R;
import com.android.plc.ui.OnWheelChangedListener;
import com.android.plc.ui.OnWheelScrollListener;
import com.android.plc.ui.adapter.AlphabetWheelAdapter;
import com.android.plc.ui.adapter.NumericWheelAdapter;
import com.android.plc.ui.view.WheelView;

public class DeviceCodeDialog extends AlertDialog implements android.view.View.OnClickListener
{
	private static final String TAG = "DeviceCodeDialog";
	OnWheelSelectListener mListener; // the callback
	private int device_code = 0x00;
	// Time changed flag
	private boolean timeScrolled = false;
	private WheelView codeA;
	private WheelView code1;

	public DeviceCodeDialog(Context context)
	{
		super(context, R.style.PickDialogTheme);
	}

	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.device_code_dialog);

		codeA = (WheelView) findViewById(R.id.room_code_A);
		codeA.setAdapter(new AlphabetWheelAdapter(0, 15));
		codeA.setVisibleItems(5);
		code1 = (WheelView) findViewById(R.id.room_code_1);
		code1.setAdapter(new NumericWheelAdapter(1, 16, null));
		code1.setVisibleItems(5);

		final Button save = (Button) findViewById(R.id.edit_save);
		save.setOnClickListener(this);
		final Button cancel = (Button) findViewById(R.id.edit_cancel);
		cancel.setOnClickListener(this);
		OnWheelChangedListener wheelListener = new OnWheelChangedListener()
		{
			public void onChanged(WheelView wheel, int oldValue, int newValue)
			{
				if (!timeScrolled)
				{
					device_code = codeA.getCurrentItem() << 4;
					device_code += code1.getCurrentItem();
				}
			}
		};

		codeA.addChangingListener(wheelListener);
		code1.addChangingListener(wheelListener);

		OnWheelScrollListener scrollListener = new OnWheelScrollListener()
		{
			public void onScrollingStarted(WheelView wheel)
			{
				timeScrolled = true;
			}

			public void onScrollingFinished(WheelView wheel)
			{
				timeScrolled = false;
				device_code = codeA.getCurrentItem() << 4;
				device_code += code1.getCurrentItem();
			}
		};

		codeA.addScrollingListener(scrollListener);
		code1.addScrollingListener(scrollListener);
	}

	public void selectDeviceCode(int deviceCode)
	{
		codeA.setCurrentItem(deviceCode / 16);
		code1.setCurrentItem(deviceCode % 16);
	}

	public void onClick(View v)
	{
		if (v.getId() == R.id.edit_save && mListener != null)
		{
			Log.d(TAG, String.format(" select %x", device_code));
			mListener.onSelected(device_code);
		}
		this.dismiss();
	}

	public void setSelectCodeListener(OnWheelSelectListener listener)
	{
		mListener = listener;
	}

}
